package com.loie.xcx.service.impl;

import com.loie.xcx.mapper.SystemMapper;
import com.loie.xcx.model.bo.PermissionBO;
import com.loie.xcx.model.bo.SysRoleBO;
import com.loie.xcx.model.bo.UserInfoBO;
import com.loie.xcx.service.PermissionService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;


/**
 * @author zhl
 */
@Service
@AllArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class PermissionServiceImpl implements PermissionService {
    final SystemMapper systemMapper;

    @SneakyThrows
    @Override
    public List<PermissionBO> getPermission(String openId, String module) {
        UserInfoBO userInfoBO = systemMapper.getUserInfoByOpenId(openId);
        List<SysRoleBO> roleBOList = systemMapper.getSysRoleByOpenId(openId);
        List<PermissionBO> permissionBOList = new ArrayList<>(roleBOList.size());

        for (SysRoleBO sysRoleBO : roleBOList) {
            if ("Administrators".equals(sysRoleBO.getName())){
                PermissionBO permissionBO = new PermissionBO();
                BeanUtils.copyProperties(sysRoleBO, permissionBO);
                permissionBO.setRange("vrAll");
                permissionBO.setUserId(userInfoBO.getUserId());
                permissionBOList.add(permissionBO);
                return permissionBOList;

            }
            byte[] permissionsByte = sysRoleBO.getPermissions();
            String permissionsXml = new String(permissionsByte, StandardCharsets.UTF_8);
//            System.out.println("XML==>" + permissionsXml);
            Document doc = DocumentHelper.parseText(permissionsXml);
            Element rootElt = doc.getRootElement();
            Node node = rootElt.selectSingleNode("//data/TcxRolePermissions/Modules/Item[@Name='" + module + "']");
            String range = node.valueOf("@Range");
            PermissionBO permissionBO = new PermissionBO();
            BeanUtils.copyProperties(sysRoleBO, permissionBO);
            permissionBO.setRange(range);
            permissionBO.setUserId(userInfoBO.getUserId());
            permissionBOList.add(permissionBO);
        }
        return permissionBOList;
    }
}
